package main

import (
	"context"
	mygrpc "e-commerce/services/product-service/api/grpc"
	"e-commerce/services/product-service/api/http"
	pb "e-commerce/services/product-service/api/pb"
	"e-commerce/services/product-service/otel"
	"log"
	"net"

	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"google.golang.org/grpc"
)

func main() {
	shutdown, err := otel.InitTracer("product-service", "services/product-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to initialize tracer: %v", err)
	}
	defer func() {
		if err := shutdown(context.Background()); err != nil {
			log.Printf("Failed to shutdown tracer: %v", err)
		}
	}()
	productHandler := http.NewProductHandler("services/product-service/config/devconfig.yaml")
	r := gin.Default()
	r.Use(otelgin.Middleware("product-service"))
	r.GET("/products/:id", productHandler.GetProduct)
	r.POST("/products", productHandler.CreateProduct)
	r.PUT("/products/:id", productHandler.UpdateProduct)
	r.DELETE("/products/:id", productHandler.DeleteProduct)
	r.GET("/products", productHandler.ListProducts)
	go r.Run(":8082")

	lis, err := net.Listen("tcp", ":50052")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	} else {
		log.Printf("server listening at %v", lis.Addr())
	}
	productServer := mygrpc.NewProductServer("services/product-service/config/devconfig.yaml")
	s := grpc.NewServer(
		grpc.StatsHandler(otelgrpc.NewServerHandler()),
		grpc.UnaryInterceptor(productServer.AuthMiddleware),
	)
	pb.RegisterProductServiceServer(s, productServer)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
